import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Col,
  Switch,
  Progress, DatePicker, Select,Tabs
} from 'antd';
import MyPagination from '@/components/MyPagination';
import Loading from '@/components/Loading';

import find from 'lodash/find';
import findIndex from  'lodash/findIndex'
import debounce from 'lodash/debounce';
import { ellipsis, afterCloseModal, DescriptionItem } from '@/utils/utils';
import { routerRedux } from 'dva/router';
import BuildModalTitle from '@/components/BuildModalTitle';
import ReactDataGrid from 'react-data-grid';
import AddOrEditUser from './addOrEditUser';
import AddOrEditStaffs from './addOrEditUser';
import Detail from './Detail';
const { TabPane } = Tabs;
const FormItem = Form.Item;
const MonthPicker =DatePicker.MonthPicker
const { confirm } = Modal;
const { Option } = Select;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ daily_analysis_report, loading, global }) => ({
  daily_analysis_report,
  global,
  loading: loading.models.daily_analysis_report,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      address:[{ name: "塔尔浪水源水"},
        { name: "塔尔浪出厂水"},
        { name: "老城区水厂出厂水"},
        { name: "示范区水厂出厂水"},
        { name: "七泉湖出厂水"},
        { name: "七泉湖进场水"},
  /*    { name: "绿园小区"},
        { name: "区住建局"},
        { name: "农科所" },
        { name: "示范区宜居园社区"},
        { name: "亚尔镇政府"},
        { name: "自来水公司" }, */
      ],
      data:[],
      activeKey:'塔尔浪水源水'
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      daily_analysis_report: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        daily_analysis_report: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'daily_analysis_report/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'daily_analysis_report/changeLoaded',
          });
          dispatch({
            type: 'daily_analysis_report/changeTableY',
          });
        },
      });

    }
    let data=[];
    for(let i=0;i<25;i++){
      data.push({
        date:moment('2021-07-01').add(i,'day').format('YYYY-MM-DD'),
        hzd:1.69,
        sd:'<5',
        rykjw:'无',chw:'无',ph:'8',xjzs:'21',zdcjq:'未检出',fdcjq:'未检出',hyl:'0.57',ad:'0.18'
      })
    }
    data.push({
      date:'限值',
      hzd:1.69,
      sd:'15',
      rykjw:'无',chw:'无',ph:'6.5-8.5',xjzs:'100',zdcjq:'≤3',fdcjq:'未检出',hyl:'≤0.5',ad:'≤0.5'
    })
    this.setState({
      data
    })
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'daily_analysis_report/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'daily_analysis_report/changeTableY',
    });
  };
  findChildFunc = (cb) => {
    this.file = cb;
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    const table = document.querySelector('.react-grid-Canvas');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'daily_analysis_report/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
      },
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      daily_analysis_report: { searchParams },
    } = this.props;
    return (
      <Form layout="inline" className="search-form">
        <FormItem>

          <FormItem label="采样月份">
            {getFieldDecorator('month', {
              initialValue: moment(searchParams.month),
            })(<MonthPicker allowClear={false} style={{ width: '150px' }} placeholder="请选择"/>)}
          </FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  month:moment(fieldsValue.month).format('YYYY-MM'),
                  sampling_location:searchParams.sampling_location
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: 'water_report_operation' }) &&
            <Button
              icon="plus"
              style={{ marginLeft: 8 }}
              type="primary"
              onClick={
                () => {
                  this.setState({
                    addModal: true,
                  });
                }
              }
            >
              {`添加"${searchParams.sampling_location}"每日分析记录`}
            </Button>
          }
        </FormItem>

      </Form>
    );
  }

  handleEdit = () => {
    const formValues = this.EditForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const {
      daily_analysis_report: { searchParams },
    } = this.props;
    let data=[]
    for(let key in formValues){
      if(key.indexOf('$')>0&&key.indexOf('限值')<0){
        console.log(key)
        let address=key.split('$')[0];
        const exit =findIndex(data,function(o) {
          return o.address===address
        })
        if(exit>=0){
          data[exit][key.split('$')[1]]=formValues[key]
        }else{
          data.push({
            address:address,
            [key.split('$')[1]]:formValues[key]
          })
        }
      }


    }
    console.log(data)
    let parseData=[]
    for(let i=0;i<data.length;i++){
      for(let key in data[i]){
        parseData.push({
          key:key,
          value:data[i][key],
        })
      }
    }
    console.log('parseData',parseData)
    const that = this;
    this.props.dispatch({
      type: 'daily_analysis_report/edit',
      payload: {
        id:this.state.editRecord.id,
        sampling_date:moment(formValues.sampling_date).format('YYYY-MM-DD'),
        sampling_location:searchParams.sampling_location,
        recorder:formValues.recorder,
        manager:formValues.manager,
        items:parseData,
      },
      callback() {
        message.success('修改日报成功');
        that.setState({
          editModal: false,
        });
        const {
          daily_analysis_report: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      sampling_location:'塔尔郎水源水',
      month:moment().format('YYYY-MM'),
    });
  };

  handleAdd = () => {
    const formValues = this.AddForm.props.form.getFieldsValue();
    console.log('formValues', formValues);
    const {
      daily_analysis_report: { searchParams },
    } = this.props;
    let data=[]
    for(let key in formValues){
      if(key.indexOf('$')>0&&key.indexOf('限值')<0){
        console.log(key)
        let address=key.split('$')[0];
        const exit =findIndex(data,function(o) {
          return o.address===address
        })
        if(exit>=0){
          data[exit][key.split('$')[1]]=formValues[key]
        }else{
          data.push({
            address:address,
            [key.split('$')[1]]:formValues[key]
          })
        }
      }


    }
    console.log(data)
    let parseData=[]
    for(let i=0;i<data.length;i++){
      for(let key in data[i]){
        parseData.push({
          key:key,
          value:data[i][key],
        })
      }
    }
    console.log('parseData',parseData)
    const that = this;
    this.props.dispatch({
      type: 'daily_analysis_report/add',
      payload: {
        sampling_date:moment(formValues.sampling_date).format('YYYY-MM-DD'),
        sampling_location:searchParams.sampling_location,
        recorder:formValues.recorder,
        manager:formValues.manager,
        items:parseData,
      },
      callback() {
        message.success('添加日报成功');
        that.setState({
          addModal: false,
        });
        const {
          daily_analysis_report: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  handleDelete = id => {
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: `daily_analysis_report/remove`,
      payload: { id },
      callback: () => {
        message.success('删除日报成功');
        const {
          daily_analysis_report: { searchParams },
        } = that.props;
        that.handleSearch(searchParams);
      },
    });
  };

  render() {
    const that = this;
    const {
      daily_analysis_report: { data, loading, tableY, meta, searchParams, selectedRowKeys },
      global: { gridTableW },
    } = this.props;
    console.log('data',data)
    const defaultColumnProperties = {
      resizable: true,
    };
    let sampling_location=searchParams.sampling_location;
    let adtitle='氨氮mg/L'
    if(sampling_location==='示范区水厂出厂水'||sampling_location==='七泉湖出厂水'||sampling_location==='七泉湖进场水'){
      adtitle='游离余氯mg/L'
    }else if(sampling_location==='塔尔浪出厂水'||sampling_location==='老城区水厂出厂水'){
      adtitle='二氧化氯mg/L'
    }else if(sampling_location==='塔尔浪水源水'){
      adtitle='氨(以N计)mg/L'
    }
    if(sampling_location==='示范区水厂出厂水'){
      adtitle='游离氯mg/L';
    }
    if(sampling_location==='七泉湖出厂水'){
      adtitle='游离氯mg/L';
    }
    if(sampling_location==='七泉湖进场水'){
      adtitle='氨(以N计)mg/L'
    }
    const columns = [
      {
        name: '日期',
        width: 120,
        key: 'sampling_date',
        frozen:true
      },
      {
        name: '浑浊度NTU',
        width: 100,
        key: 'hzd',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='hzd')){
            return  ''
          }
          let value=Number(find(event.row.items,o=>o.key==='hzd').value);
          if(value>1){
            return find(event.row.items,o=>o.key==='hzd').value
          }else{
            return find(event.row.items,o=>o.key==='hzd').value
          }
        }
      },
      {
        name: '色度',
        width: 80,
        key: 'sd',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='sd')){
            return  ''
          }
          let value=Number(find(event.row.items,o=>o.key==='sd').value);
          if(value>15){
            return <p className={'table-error table-status'}>{find(event.row.items,o=>o.key==='sd').value}</p>
          }else{
            return find(event.row.items,o=>o.key==='sd').value
          }
        }
      },
      {
        name: '肉眼可见物',
        width: 100,
        key: 'rykjw',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='rykjw')){
            return  ''
          }
          let value=find(event.row.items,o=>o.key==='rykjw').value;
          if(value==='无'||value==='-'||value==='--'){
            return value

          }else{
            return <p className={'table-error table-status'}>{value}</p>
          }
        }
      },
      {
        name: '臭和味',
        width: 100,
        key: 'chw',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='chw')){
            return  ''
          }
          let value=find(event.row.items,o=>o.key==='chw').value;
          if(value==='无'||value==='-'||value==='无异臭、异味'||value==='--'){
            return value

          }else{
            return <p className={'table-error table-status'}>{value}</p>
          }
        }
      },
      {
        name: 'PH值',
        width: 80,
        key: 'ph',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='ph')){
            return  ''
          }
          let value=Number(find(event.row.items,o=>o.key==='ph').value);
          if(value<6||value>9){
            return <p className={'table-error table-status'}>{find(event.row.items,o=>o.key==='ph').value}</p>
          }else{
            return find(event.row.items,o=>o.key==='ph').value
          }
        }
      },
      {
        name: '细菌总数CFU/mL',
        width: 140,
        key: 'xjzs',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='xjzs')){
            return  ''
          }
          let value=Number(find(event.row.items,o=>o.key==='xjzs').value);
          if(value>100){
            return <p className={'table-error table-status'}>{find(event.row.items,o=>o.key==='xjzs').value}</p>
          }else{
            return find(event.row.items,o=>o.key==='xjzs').value
          }
        }
      },
      {
        name: '总大肠菌群MPN/100mL',
        width: 180,
        key: 'zdcjq',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='zdcjq')){
            return  ''
          }
          let value=find(event.row.items,o=>o.key==='zdcjq').value;
          if(event.row.sampling_date==='限值'){
            return value
          }
          if(value!=='未检出'&&value!=='/'){
            return <p className={'table-error table-status'}>{value}</p>
          }else{
            return value
          }
        }
      },
      {
        name: '耐热大肠菌群MPN/100mL',
        width: 180,
        key: 'fdcjq',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='fdcjq')){
            return  ''
          }
          let value=find(event.row.items,o=>o.key==='fdcjq').value;
          if(event.row.sampling_date==='限值'){
            return value
          }
          if(value!=='未检出'&&value!=='/'){
            return <p className={'table-error table-status'}>{value}</p>
          }else{
            return value
          }
        }
      },
      {
        name: '高锰酸盐指数(以O2计)',
        width: 150,
        key: 'hyl',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='hyl')){
            return  ''
          }
          let value=Number(find(event.row.items,o=>o.key==='hyl').value);
          if(value>3){
            return <p className={'table-error table-status'}>{find(event.row.items,o=>o.key==='hyl').value}</p>
          }else{
            return find(event.row.items,o=>o.key==='hyl').value
          }
        }
      },
      {
        name: adtitle,
        width: 120,
        key: 'ad',
        formatter:(event)=>{
          if(!find(event.row.items,o=>o.key==='ad')){
            return  ''
          }
          let value=Number(find(event.row.items,o=>o.key==='ad').value);
          let sampling_location=searchParams.sampling_location;

          if(sampling_location==='示范区水厂'){
            if(value>4||value<0.3){
              return <p className={'table-error table-status'}>{find(event.row.items,o=>o.key==='ad').value}</p>
            }else{
              return find(event.row.items,o=>o.key==='ad').value
            }
          }else if(sampling_location==='塔尔郎水厂出厂水'||sampling_location==='老城区水厂出厂水'){
            if(value>0.8||value<0.1){
              return <p className={'table-error table-status'}>{find(event.row.items,o=>o.key==='ad').value}</p>
            }else{
              return find(event.row.items,o=>o.key==='ad').value
            }
          }else{
            if(value>0.8){
              return <p className={'table-error table-status'}>{find(event.row.items,o=>o.key==='ad').value}</p>
            }else{
              return find(event.row.items,o=>o.key==='ad').value
            }
          }

        }
      },
      {
        name: '记录人',
        width: 100,
        key: 'recorder',
      },
      {
        name: '负责人',
        width: 100,
        key: 'manager',
      },
      {
        name: '操作',
        width: 180,
        key: 'right',
        classname: 'operate',
        formatter: (event) => <Fragment>
          {
            (find(this.permissions, { name: 'water_report_operation' })&&event.row.sampling_date!=='限值') &&
          <Fragment>

            <Button
              type="primary"
              size="small"
              icon="edit"
              onClick={(e) => {
                this.setState({
                  editRecord:event.row,
                  editModal:true
                })
              }
              }
            >修改
            </Button>
              <Button
                type="danger"
                size="small"
                icon="delete"
                onClick={(e) => {
                  confirm({
                    title: `确定要删除"${event.row.sampling_date}"记录吗?`,
                    content: '请谨慎操作！',
                    okText: '确定',
                    okType: 'danger',
                    cancelText: '取消',
                    centered:true,
                    maskClosable: true,
                    onOk() {
                      that.handleDelete(event.row.id);
                    },
                    onCancel() {
                      console.log('Cancel');
                    },
                  });
                }
                }
              >删除
              </Button>

          </Fragment>
          }

        </Fragment>,
      },

    ].map(c => ({ ...defaultColumnProperties, ...c }));

    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if (totalWidth < gridTableW) {
      columns[columns.length - 1].width = columns[columns.length - 1].width + gridTableW - totalWidth;
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>常规分析报告(日检)</span>
      </div>
      <div className="table-page">
        <div className="table-condition">{this.renderSimpleForm()}</div>

        <div className={'table-data-content'}>
          <Tabs type="card" activeKey={searchParams.sampling_location} onChange={(activeKey)=>{
            this.handleSearch({
              sampling_location:activeKey,
              month:searchParams.month
            })
          }}>
            {
              this.state.address.map((item,index)=>{
                return <TabPane tab={item.name} key={item.name}>
                </TabPane>
              })
            }

          </Tabs>
          <ReactDataGrid
            columns={columns}
            rowGetter={i => {
              return { ...data[i], _index: i };
            }}
            rowsCount={data.length}
            onGridRowsUpdated={this.onGridRowsUpdated}
            minHeight={tableY}
            rowSelection={{
              showCheckbox: false,
              enableShiftSelect: true,
              selectBy: {
                indexes: selectedRowKeys,
              },
            }}
            onRowClick={
              (row) => {
                this.props.dispatch({
                  type: 'daily_analysis_report/changeSelectRow',
                  payload: [row],
                });
              }
            }

          />
          {
            loading && <Loading/>
          }
        </div>


      </div>
      <Modal
        title={<BuildModalTitle visible={this.state.addModal} modalClass="addModal"
                                title={`添加每日分析记录`}/>}
        className="addModal"
        destroyOnClose
        visible={this.state.addModal}
        centered
        width={560}
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        onCancel={() => {
          this.setState({ addModal: false });
        }}
        onOk={this.handleAdd}
      >
        <AddOrEditUser
          activeKey={searchParams.sampling_location}
          wrappedComponentRef={(inst) => this.AddForm = inst}/>

      </Modal>
      <Modal
        title={<BuildModalTitle visible={this.state.editModal} modalClass="editModal"
                                title={`修改 ${this.state.editRecord.sampling_date}`}/>}
        destroyOnClose
        visible={this.state.editModal}
        centered
        onOk={this.handleEdit}
        className="editModal"
        afterClose={() => {
          afterCloseModal(); // destroyOnClose需要
        }}
        width={560}
        onCancel={() => {
          this.setState({ editModal: false, editRecord: {} });
        }}

      >
        <AddOrEditUser
          editRecord={this.state.editRecord}
          activeKey={searchParams.sampling_location}
          wrappedComponentRef={(inst) => this.EditForm = inst}
        />

      </Modal>
    </div>;
  }
}

export default BasicList;
